<?php
if (!function_exists('GetVersion')) {
	/**
	 * 获取当前
	 * @return string
	 */
	function GetVersion()
	{
		return app()->version();
	}
}

if (!function_exists('DieDump')) {
	/**
	 * 断点输出
	 * @param $var
	 * @param bool $isJson
	 */
	function DieDump($var, $isJson = false)
	{
		if ($isJson) {
			die(json_encode($var, 256));
		} else {
			var_dump($var);
			die();
		}
	}
}

if (!function_exists('CreateToken')) {
	/**
	 * 创建用户TOKEN
	 * @param int $userId
	 * @return array
	 * @throws Exception
	 */
	function CreateToken($userId = 0)
	{
        list($usec, $sec) = explode(" ", microtime());
        $timeSec = ((float)$usec + (float)$sec);
		$time = uniqid($userId) . $timeSec;
		$rand = random_int(0, 1000);
		$token = md5(md5($time) . md5($rand));
		$cryptToken = \Illuminate\Support\Facades\Crypt::encryptString($token);
		return compact('token', 'cryptToken');
	}
}

if (!function_exists('ApiReturn')) {
	/**
	 * 获取API返回固定格式
	 * @param string $status
	 * @param string $info
	 * @param array $data
	 * @param int $code
	 * @return false|string
	 */
	function ApiReturn($status='YES', $info='', $data=[], $code=RETURN_SUCCESS) {
	    if (is_array($status)) {
	        try {
                return json_encode([
                    'status'    =>  $status['code'],
                    'info'      =>  $status['msg'],
                    'data'      =>  $status['data'],
                    'code'      =>  $status['httpCode']
                ], 256);
            } catch (\Throwable $e) {
                throw new \Exception('API RETURN FORMAT FAIL', RETURN_FAIL);
            }
        }
		return json_encode(compact('status', 'info', 'data', 'code'), 256);
	}
}

if (!function_exists('ModelReturn')) {
	/**
	 * 模型内部返回固定格式
	 * @param int $code
	 * @param string $msg
	 * @param array $data
	 * @return array
	 */
	function ModelReturn($code = RETURN_SUCCESS, $msg= '', $data=[]) {
        $httpCode = (int)$code;
        $code = $code == RETURN_SUCCESS ? "YES" : "NO";
		return compact('code', 'msg', 'data', 'httpCode');
	}
}

if (!function_exists('ArrToSql')) {
	/**
	 * 数组转换为SQL查询语句的in条件
	 * @param $arr
	 * @return string
	 */
	function ArrToSql($arr)
	{
		$str = sprintf("('%s')", implode("','", $arr));
		return $str;
	}
}

if (!function_exists('HandleLog')) {
	/**
	 * 获取处理所有日志信息log对象
	 * @return \App\Common\ScarecrowProvider\ScarecrowDoLogProvider|string
	 * @throws Exception
	 */
	function HandleLog()
	{
		return \App\Common\ScarecrowProvider\ScarecrowDoLogProvider::getExample();
	}
}

if (!function_exists('DbObjectToArr')) {
	/**
	 * DB返回的对象数据转为数组
	 * @param $data
	 * @return mixed
	 */
	function DbObjectToArr($data)
	{
		return json_decode(json_encode($data), true);
	}
}

if (!function_exists('ReadAllFiles')) {
	/**
	 * 获取文件夹下的所有文件名称（文件夹与文件有关联关系）
	 * @param $dirPath
	 * @return array
	 */
	function ReadAllFiles($dirPath) {
		$result = [];
		$handle = opendir($dirPath);
		if ( $handle )
		{
			while ( ( $file = readdir ( $handle ) ) !== false )
			{
				if ( $file != '.' && $file != '..')
				{
					$cur_path = $dirPath .'/'.$file;
					if ( is_dir ( $cur_path ) )
					{
						$result['dir'][$file] = ReadAllFiles ( $cur_path );
					}
					else
					{
						$result['file'][$file] = $cur_path;
					}
				}
			}
			closedir($handle);
		}
		$result['basePath'] = $dirPath;
		return $result;
	}
}

if (!function_exists('ReadAllDirAndFiles')) {
	/**
	 * 获取文件夹下的所有文件名称（文件夹与文件无关联关系）
	 * @param string $basePath
	 * @return array|bool
	 */
	function ReadAllDirAndFiles($basePath = '') {
		$allDir = [];
		$allFile = [];

		$basePath = realpath($basePath);
		if ($basePath === false) {
			return false;
		}

		$allDir[] = $basePath;
		$allHandleDir = $allDir;

		while (!empty($allHandleDir)) {
			$basePathTemp = array_pop($allHandleDir);
			$allObj = scandir($basePathTemp);

			foreach ($allObj as $item) {
				if ($item == '.' || $item == '..') {
					continue;
				}

				$path = $basePathTemp . '/' . $item;
				if (is_dir($path)) {
					$allDir[] = $path;
					$allHandleDir[] = $path;
				} else {
					$allFile[] = $path;
				}
			}
		}

		return [
			'dir'   =>  $allDir,
			'file'  =>  $allFile
		];
	}
}

if (!function_exists('CurlPost')) {
    /**
     * CURL POST请求
     * @param $url
     * @param $data
     * @param $header
     * @param bool $isSsl
     * @return bool|string
     * @throws \Exception
     */
    function CurlPost($url, $data, $header = [], $isSsl = false, $certs = ['apiclient_cert' => '', 'apiclient_key' => '', 'cacert' => ''])
    {
        $ch = curl_init();
        $timeout = 600;
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        if ($isSsl) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);//证书检查
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
//			curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).'/../cert/apiclient_cert.pem');
            curl_setopt($ch, CURLOPT_SSLCERT, $certs['apiclient_cert']);
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
//			curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).'/../cert/apiclient_key.pem');
            curl_setopt($ch, CURLOPT_SSLCERT, $certs['apiclient_key']);
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
//			curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).'/../cert/cacert.pem');
            curl_setopt($ch, CURLOPT_SSLCERT, $certs['cacert']);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $reponse = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new \Exception(curl_error($ch), RETURN_SOCKET_FAIL);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                throw new \Exception($reponse, RETURN_SOCKET_FAIL);
            }
        }
        curl_close($ch);
        return $reponse;
    }
}

if (!function_exists('CurlGet')) {
    /**
     * CURL GET请求
     * @param $url
     * @return bool|string
     * @throws \Exception
     */
    function CurlGet($url, $header = [])
    {
        $curl = curl_init();
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        $reponse = curl_exec($curl);
        if (curl_errno($curl)) {
            throw new \Exception(curl_error($curl), RETURN_SOCKET_FAIL);
        } else {
            $httpStatusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                throw new \Exception($reponse, RETURN_SOCKET_FAIL);
            }
        }
        curl_close($curl);
        return $reponse;
    }
}

if (!function_exists('CurlPostFile')) {
    /**
     * CURL 数据流形式上传文件（发送数据流到指定地址）
     */
    function CurlPostFile($uri, $fileContent) {
        //必须用个载体来存储成文件让后使用CURLFile来进行数据流的发送
        $fileTemp = storage_path("/temp/test.txt");
        file_put_contents($fileTemp, $fileContent);
        $body = ['file'=>new \CURLFile($fileTemp, '', 'file')];
        $relData = CurlPost($uri, $body);
        @unlink($fileTemp);
        return $relData;
    }
}

if (!function_exists('DeleteDir')) {
    /**
     * 删除文件夹
     * @param $dir
     * @return bool
     */
    function DeleteDir($dir) {
        if (!is_dir($dir)) {
            return false;
        }

        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullPath=$dir."/".$file;
                if(!is_dir($fullPath)) {
                    @unlink($fullPath);
                } else {
                    DeleteDir($fullPath);
                }
            }
        }
        closedir($dh);
        if(@rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('isEmail')) {
    /**
     * 判定是否是邮箱地址
     * @param $address
     * @return bool
     */
    function isEmail($address) {
        return filter_var($address, FILTER_VALIDATE_EMAIL) === false ? false : true;
    }
}